import unittest
import requests
from ddt import ddt, data, unpack

BASE_URL = "http://127.0.0.1:8001"

# 测试增加数据
TEST_USER_ADD = {
    'name': '张三',
    'age': '30',
    'gender': '男',
    'phone': '13800138000'
}

# 修改的用户数据 
TEST_USER_EDIT = {
    'id': '1',
    'name': '李四',
    'age': '25',
    'gender': '女',
    'phone': '13900139000'
}

#删除的用户ID
remove_user_id = 1

@ddt
class TestFlaskCRUD(unittest.TestCase):

    def test_01_index(self):
        """测试首页加载"""
        response = requests.get(f"{BASE_URL}/")
        self.assertEqual(response.status_code, 200)
        print("接口测试成功：test_01_index")

    def test_02_search(self):
        """测试搜索功能"""
        params = {'keyword': '妲己'}
        response = requests.get(f"{BASE_URL}/search", params=params)
        self.assertEqual(response.status_code, 200)
        print("接口测试成功：test_02_search")

    @data(TEST_USER_ADD)
    def test_03_add_user(self, user_data):
        """测试添加用户"""
        try:
            response = requests.post(f"{BASE_URL}/add", data=user_data)
            self.assertIn(response.status_code, [200, 302])
            print("接口测试成功：test_03_add_user")
        except Exception as e:
            print("接口测试失败：test_03_add_user -", str(e))

    @data(TEST_USER_EDIT)
    def test_04_edit_user(self, user_data):
        """测试编辑用户"""
        try:
            response = requests.post(f"{BASE_URL}/edit", data=user_data)
            self.assertIn(response.status_code, [200, 302])
            print("接口测试成功：test_04_edit_user")
        except Exception as e:
            print("接口测试失败：test_04_edit_user -", str(e))

    def test_05_remove_user(self):
        """测试删除用户"""
        try:
            user_id = remove_user_id
            response = requests.get(f"{BASE_URL}/remove/{user_id}")
            self.assertIn(response.status_code, [200, 302])
            print("接口测试成功：test_05_remove_user")
        except Exception as e:
            print("接口测试失败：test_05_remove_user -", str(e))

    def test_06_404_page(self):
        """测试不存在的页面是否返回 404"""
        try:
            response = requests.get(f"{BASE_URL}/invalid-route")
            self.assertEqual(response.status_code, 404)
            print("接口测试成功：test_06_404_page")
        except Exception as e:
            print("接口测试失败：test_06_404_page -", str(e))

if __name__ == '__main__':
    unittest.main(verbosity=2)